package processor

import (
	"strings"

	"github.com/cheggaaa/pb/v3"
	log "github.com/sirupsen/logrus"
	"github.com/twang2218/herbs/common"
)

func Statistics(herbs common.Herbs, pres common.Prescriptions) {
	statsHerbsByOrigin(herbs)

	//	按照名称长度倒叙、拼音排序
	log.Info("按照药材名称长度（倒叙）、拼音（正序）排序")
	herbs.Sort()
	for i := 0; i < 10; i++ {
		log.Infof("    %.10s    (%.2d) %s", herbs[i].Name, len(herbs[i].Descriptions), herbs[i].Descriptions[0].Book)
	}

	statsPresByOrigin(pres)

	//	按照方剂名称排序
	log.Info("按照方剂拼音（正序）排序")
	pres.Sort()
	for i := 0; i < 10; i++ {
		log.Infof("    %.10s    (%.2d) %s", pres[i].Name, len(pres[i].Descriptions), pres[i].Descriptions[0].Origin)
	}

	log.Info("处理解析方剂配方")
	bar := pb.StartNew(len(pres))
	for i1, p := range pres {
		bar.Increment()
		for i2, d := range p.Descriptions {
			d.RecipeProcessed = processRecipe(d.Recipe, herbs)
			p.Descriptions[i2] = d
		}
		pres[i1] = p
	}
	bar.Finish()

	log.Info("获得出现在方剂的药材名称")
	usedMedNames := map[string]bool{}
	for _, p := range pres {
		for _, d := range p.Descriptions {
			mas := strings.Split(d.RecipeProcessed, ",")
			for _, ma := range mas {
				ms := strings.Split(ma, "/")
				m := ms[0]
				usedMedNames[m] = true
			}
		}
	}
	log.Infof("总共有 %d 种药材，出现在 %d 个方剂中的有 %d 种药材。", len(herbs), len(pres), len(usedMedNames))
}

/********************************************************************/

func statsHerbsByOrigin(herbs common.Herbs) error {
	var counters common.NameCounters
	for _, h := range herbs {
		for _, d := range h.Descriptions {
			counters.Add(d.Book)
		}
	}
	counters.Sort()

	log.Infof("所有药材来自 %d 本书籍，其中收录最多药材的书籍如下：", len(counters))
	log.Infof(">     排名     书籍名          收录药材数")
	for i, o := range counters {
		if i >= 10 {
			break
		}

		log.Infof(">     [%d]     《%.10s》      %d", i+1, o.Name, o.Count)
	}

	return nil
}

/********************************************************************/

func statsPresByOrigin(pres common.Prescriptions) error {
	var counters common.NameCounters
	for _, p := range pres {
		for _, d := range p.Descriptions {
			counters.Add(d.Book)
		}
	}
	counters.Sort()

	log.Infof("所有方剂来自 %d 本书籍，其中收录最多方剂的书籍如下：", len(counters))
	log.Infof(">     排名     书籍名          收录方剂数")
	for i, o := range counters {
		if i >= 10 {
			break
		}

		log.Infof(">     [%d]     《%.20s》      %d", i+1, o.Name, o.Count)
	}

	return nil
}

/********************************************************************/
